# 监测IT运维的各种设备是否在线
#!/usr/bin/python3

import os
import time
import threading
import requests
import json

# 企业微信告警消息发送函数
def send_warning_message(ip, device_name):
    url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=******'
    headers = {
        'Content-Type': 'application/json',
    }
    data = {
        "msgtype": "text",
        "text": {
            "content": f"告警：{device_name} ({ip}) 不可达，请注意！",
            "mentioned_mobile_list":["", "@all"]
        }
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))
    # 静默运行，不打印响应状态码，可以通过企业微信消息确认发送成功

# 定义IP地址和设备名称的映射
IP_DEVICES = {
    "10.210.7.6": "服务器01",
    "10.210.7.7": "服务器02",
}

# 检测IP是否可达
def ping_ip(ip):
    command = f"ping -n 1 -w 5000 {ip}"
    result = os.popen(command).read()
    return "TTL" in result

# 监控单个IP
def monitor_ip(ip, device_name):
    while True:
        if not ping_ip(ip):
            send_warning_message(ip, device_name)  # 如果IP不可达，发送告警消息
        time.sleep(60)  # 每60秒检查一次

# 启动多线程监控所有IP
def start_monitoring():
    threads = []
    for ip, device_name in IP_DEVICES.items():
        thread = threading.Thread(target=monitor_ip, args=(ip, device_name))
        threads.append(thread)
        thread.start()

if __name__ == "__main__":
    start_monitoring()

# nohup python /root/device_active.py &  可以确保后台静默运行
# start /min python C:\Users\Administrator\Desktop\share\device_active.py